/**
 * 重写jquery 的ajax方法。加入csrf跨站攻击的token植入和错误信息的处理
 * 因为jquery.load实际是调用$.ajax，故可以不用重写
 * Created by 杨浩宇 on 2016/2/29 0029.
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // CommonJS
        factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {
    //获取页面的<meta name="_csrf" content="${_csrf.token}"/>以及<meta name="_csrf_header" content="${_csrf.headerName}"/>
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    var _ajax = $.ajax;
    $.ajax = function (opt) {
        var fn = {
            success: opt.success ? opt.success : function (data, textStatus) {
            },
            error: opt.error ? opt.error : function (XMLHttpRequest, textStatus, errorThrown) {
            },
            beforeSend: opt.beforeSend ? opt.beforeSend : function (XMLHttpRequest, settings) {
            }
        };
        //opt.dataType = opt.dataType || 'json';
        //opt.type = opt.type || 'POST';
        //重写$.ajax的设置参数
        var _opt = $.extend(opt, {
            success: function (data, textStatus) {
                if (jQuery.type(data).toString() == "string" && data.indexOf("errorCode") > 0) {
                    data = JSON.parse(data);
                }
                if (data != undefined && data.errorMsg != null && data.errorMsg != undefined && data.errorMsg != "") {
                    data.errorMsg = $.trim(data.errorMsg);
                    if (data.errorCode == 403 && data.url != null) { //增加SESSION失效自动跳转的判断
                        window.location = data.url;
                    } else {
                        $.alertErrorMessage(data.errorMsg);
                    }

                } else {
                    fn.success(data, textStatus);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (XMLHttpRequest.status != 200 && XMLHttpRequest.status != 404) {
                    var obj = null;
                    try {
                        obj = JSON.parse(XMLHttpRequest.responseText);
                    } catch (e) {
                        $.alertErrorMessage(XMLHttpRequest.responseText);
                    }
                    var errorMsg = obj.errorMsg ? obj.errorMsg : "无";
                    var message = "错误信息： " + errorMsg;
                    $.alertErrorMessage(message);
                }
                fn.error(XMLHttpRequest, textStatus, errorThrown);
            },
            beforeSend: function (XMLHttpRequest, settings) {
                if (token && header) {
                    XMLHttpRequest.setRequestHeader(header, token);
                }
                fn.beforeSend(XMLHttpRequest, settings);
            }
        });
        // 返回ajax  可链式调用
        return _ajax(_opt);
    };
    $.alertErrorMessage = function (message) {
        if ($("#errorMsg").length > 0) {
            $("#errorMsg").show();
            $("#errorMsg").children('span').text(message);
        } else {
            $.messager.defaults.ok = '确定';
            $.messager.alert("错误", message, "error");
        }
    };
    /**
     * 使用easyui的messager弹出提示信息
     * @param msg
     * @param icon (可用值有：error,question,info,warning)
     * @param title
     * @param closeFn
     */
    $.messagerShow = function (msg, icon, title, closeFn) {
        if (msg) {
            $.messager.alert({
                title: title === undefined ? "提示" : title,
                msg: msg,
                icon: icon === undefined ? "info" : icon,
                fn: closeFn === undefined ? function () {
                } : closeFn()
            });
        }
    };
    /*自定义ajax请求*/
    $.customAjax = function (url, success, data, type, async, error) {
        if (url) {
            $.ajax({
                url: url,
                async: async ? async : false,//是否为同步
                contentType: 'application/json',
                data: data ? JSON.stringify(data) : [],
                type: type ? type : 'GET',
                success: function (e) {
                    success(e);
                },
                error: function (e) {
                    error(e);
                }
            });
        }
    };
    $.fn.serializeJson = function () {
        var serializeObj = {};
        $(this.serializeArray()).each(function () {
            serializeObj[this.name] = this.value;
        });
        return serializeObj;
    };
    $.fn.serializeJsonStr = function () {
        var serializeObj = {};
        $(this.serializeArray()).each(function () {
            serializeObj[this.name] = this.value;
        });
        return JSON.stringify(serializeObj);
    };
}));
